package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.model.BannerModel;
import com.pengcheng.taskapplication.model.DeviceStatusModel;
import com.pengcheng.taskapplication.model.SubscribeOrderModel;
import com.pengcheng.taskapplication.model.WashOrderModel;
import com.pengcheng.taskapplication.model.WashTypeModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenterV2;
import com.pengcheng.taskapplication.mvp.view.fragment.DialogFragmentFromBottom;
import com.pengcheng.taskapplication.mvp.view.fragment.DialogFragmentWashType;
import com.pengcheng.taskapplication.net.ConvertUtil;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * Created by ZFT on 2020/10/28.
 */

public class ParkWashActivity extends BaseActivity implements IView, DialogFragmentWashType.OnFragmentInteractionListener {

    @BindView(R.id.tv_center_title)
    TextView tv_center_title;

    @BindView(R.id.img_show)
    ImageView img_show;

//    @BindView(R.id.top_banner)
//    MZBannerView topZannerView;


    ArrayList<WashTypeModel> washTypeModelArrayList = new ArrayList<>();
    private UserPresenterV2 userPresenter;

    private static final int REQUEST_CODE = 124;

    private String uid;
    private String newtoken;
    private String washid = "";
    private String deviceid = "";

    @Override
    protected int layoutResID() {
        return R.layout.activity_washing_layout;
    }

    @Override
    protected void initData() {
        tv_center_title.setText("智慧洗车");
        userPresenter = new UserPresenterV2(this);
        uid = SPUtils.getString(context, ConstantValue.SpType.userid);
        newtoken = SPUtils.getString(context, ConstantValue.SpType.newtoken);
        img_show.setVisibility(View.GONE);
        // getBanner();
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {

        if (actionType.equals(ConstantValue.RequestKey.createWashOrder)) {
            WashOrderModel washOrderModel = (WashOrderModel) data;
            Intent intent = new Intent(context, WashConfrimOrderActivity.class);
            intent.putExtra("tradno", washOrderModel.getTradno());
            startActivity(intent);
            ParkWashActivity.this.finish();
        }
        if (actionType.equals(ConstantValue.RequestKey.getwashoption)) {
            ArrayList<WashTypeModel> list = (ArrayList<WashTypeModel>) data;
            washTypeModelArrayList.clear();
            washTypeModelArrayList.addAll(list);
        }


        if (actionType.equals(ConstantValue.RequestKey.getBanner)) {
            ArrayList<BannerModel> bannerModels = (ArrayList<BannerModel>) data;
            // setTopBanner(bannerModels);
        }

        if (actionType.equals(ConstantValue.RequestKey.getDeviceStatus)) {
            DeviceStatusModel deviceStatusModel = (DeviceStatusModel) data;
            String carready=deviceStatusModel.getCarready();
            String washing=deviceStatusModel.getWashing();
            String washdong=deviceStatusModel.getWashdone();
            if(carready.equals("0")&&washing.equals("0")&&washdong.equals("0")){
                //当前设备空载
                ToastUtils.showShortToast("车辆没有停到位，请按照指示灯要求停车入位");
                return;
            }
            if(carready.equals("1")&&washing.equals("0")&&washdong.equals("0")){
                //停好车了
                Intent intent =new Intent(context,WashCommitActivity.class);
                intent.putExtra("washid", washid);
                intent.putExtra("deviceid", deviceid);
                startActivity(intent);
            }
            if(carready.equals("0")&&washing.equals("1")&&washdong.equals("0")){
                //洗车中
                ToastUtils.showShortToast("车辆正在清洁中，请等待");
                return;
            }
            if(carready.equals("0")&&washing.equals("0")&&washdong.equals("1")){
                //洗车完成

            }

//            //当前设备没有订单
//            if (deviceStatusModel.getCurrenttradno().length() == 0) {
//                if (deviceStatusModel.carready.equals("0")) {
//                    ToastUtils.showShortToast("车辆没有停到位，请按照指示灯要求停车入位,请重新扫码");
//                } else if (deviceStatusModel.carready.equals("1")) {
//                    //停车到位
//                    if (deviceStatusModel.washing.equals("1")) {
//                        ToastUtils.showShortToast("已有车辆在洗车，请等待");
//                    } else if (deviceStatusModel.washing.equals("0")) {
//                        Intent intent = new Intent(context, WashCommitActivity.class);
//                        intent.putExtra("washid", washid);
//                        intent.putExtra("deviceid", deviceid);
//                        startActivity(intent);
//                    }
//                }
//            } else {
//                ToastUtils.showShortToast("当前设备有未完成的订单，不可驶入");
//            }
        }

    }


    @Override
    public void onFailed(String code, String msg) {

    }
//    private void setTopBanner(List<BannerModel> banners){
//        topZannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                //Log.e("zw","onPageScrolled---->"+position);
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
//        topZannerView.setPages(banners, new MZHolderCreator<TopBannerViewHolder>() {
//            @Override
//            public TopBannerViewHolder createViewHolder() {
//                return new TopBannerViewHolder();
//            }
//        });
//
//       // topZannerView.start();
//        topZannerView.setIndicatorVisible(true);
//
//    }

    @OnClick({R.id.img_back, R.id.img_show, R.id.ll_scan})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_show:
                //进入订单列表页面
                intent = new Intent(context, MyParkAndWashList.class);
                startActivity(intent);
                break;
            case R.id.ll_scan:
                //进入扫码页面
                //进入扫码页面,判断权限
                AndPermission.with(this)
                        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Intent intent = new Intent(context, QrScanActivity.class);
                                startActivityForResult(intent, REQUEST_CODE);
                            }
                        })
                        .onDenied(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                Toast.makeText(context, "没有权限", Toast.LENGTH_LONG).show();
                            }
                        }).start();
                break;
        }
    }

    void showDialog(ArrayList<WashTypeModel> washTypeModelArrayList) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        // Create and show the dialog.
        DialogFragmentWashType newFragment = DialogFragmentWashType.newInstance(washTypeModelArrayList);
        newFragment.show(ft, "dialog");
    }

    public void getwashoption() {
        userPresenter.getwashoption("", "", ConstantValue.RequestKey.getwashoption);
    }


    public void createWashOrder(String token, String uid, String washid, String deviceid, String washtype) {
        userPresenter.createWashOrder(token, uid, washid, deviceid, washtype, ConstantValue.RequestKey.createWashOrder);
    }

    public void geDeviceStatus(String token, String uid, String deviceid) {
        userPresenter.getStatus(token, uid, deviceid, ConstantValue.RequestKey.getDeviceStatus);
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onDelete() {

    }


    @Override
    public void onCompete(WashTypeModel model) {
        //监听选择哪个价格  下单，调用生成订单的接口，根据订单的返回，跳转到确认页面
        if (washid.length() != 0 && deviceid.length() != 0) {
            createWashOrder(newtoken, uid, washid, deviceid, model.getOptionkey());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    //根据二维码中的信息，获取相关信息
                    //校验是不是json串
                    if (ConvertUtil.validate(result)) {
                        try {
                            JsonObject jsonObject = (JsonObject) new JsonParser().parse(result).getAsJsonObject();
                            String type = jsonObject.get("type").getAsString();
                            if (type.equals("wash")) {
                                //获取停车场的id
                                washid = jsonObject.get("washid").getAsString();
                                deviceid = jsonObject.get("deviceid").getAsString();
                                //解析成功后，扫出码中信息，然后弹窗,缓存下
                                //扫码出设备id需要判断设备准备好
                                geDeviceStatus(newtoken, uid, deviceid);
                                //showDialog(washTypeModelArrayList);
                            }
                        } catch (Exception e) {
                            ToastUtils.showShortToast("解析异常，请重试");
                            washid = "";
                            deviceid = "";
                        }
                    }


                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(context, "解析二维码失败,请重新扫码", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    public void getBanner() {
        userPresenter.getBanner(ConstantValue.RequestKey.getBanner);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //    topZannerView.pause();
    }
}
